package com.shop.shop_end.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shop.shop_end.constant.OrderStatusEnum;
import com.shop.shop_end.entity.Order;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.mapper.OrderMapper;
import com.shop.shop_end.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.shop_end.utils.CommonUtil;
import com.shop.shop_end.utils.DateUtils;
import com.shop.shop_end.utils.GenerateIdUtil;
import com.shop.shop_end.utils.GenerateOrderNumUtil;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.variable.EnableVariable;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.vo.OrderVo;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2024-04-23
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CommonUtil commonUtil;

    /**
     * 增加一个订单
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Result addOneOrder(Order order) {
        order.setOrderId(GenerateIdUtil.generateId());
        order.setOrderNum(GenerateOrderNumUtil.generateOrderNum());//生成订单号
        order.setCreateTime(new Date());
        try {
            logger.info("开始生成一个订单");
            int insert = this.orderMapper.insert(order);
            if (insert == EnableVariable.UNABLE){
                logger.info("插入订单失败");
                return ResultUtil.fail("插入订单失败");
            }
        }catch (Exception e){
            logger.info("插入订单出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_UPDATE_ERROR, "插入订单出现异常");
        }
        logger.info("增加成功");
        return ResultUtil.ok("增加成功");
    }

    /**
     * 根据id删除订单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteOrderById(Long id) {
        logger.info("orderId==>{}", id);
        try {
            logger.info("开始删除id为{}的订单", id);
            int delete = this.orderMapper.deleteOrderById(id);
            if (delete == EnableVariable.UNABLE){
                logger.info("删除订单失败");
                return ResultUtil.fail("删除订单失败");
            }
        }catch (Exception e){
            logger.info("删除订单出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_DELETE_ERROR, "删除订单出现异常");
        }
        logger.info("删除成功");
        return ResultUtil.ok("删除成功");
    }

    /**
     * 修改订单信息
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Result updateOrder(Order order) {
        logger.info("order==>{}", order);
        try {
            logger.info("开始修改id为{}的订单", order.getOrderId());
            int update = this.orderMapper.updateById(order);
            if (update == EnableVariable.UNABLE){
                logger.info("修改订单失败");
                return ResultUtil.fail("修改订单失败");
            }
        }catch (Exception e){
            logger.info("修改订单出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_UPDATE_ERROR, "修改订单出现异常");
        }
        logger.info("修改成功");
        return ResultUtil.ok("修改成功");
    }

    /**
     * 查询所有订单
     * @return
     */
    @Override
    public List<OrderVo> getAllOrder() {
        logger.info("开始查询所有订单信息");
        List<Order> orderList = this.orderMapper.selectAllOrder();
        List<OrderVo> orderVoList = new ArrayList<>();
        orderList.forEach((item)->{
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderId(item.getOrderId());
            orderVo.setOrderNum(item.getOrderNum());
            orderVo.setCreateTime(DateUtils.format(item.getCreateTime(), DateUtils.DATE_TIME_PATTERN));
            orderVo.setUpdateTime(DateUtils.format(item.getUpdateTime(), DateUtils.DATE_TIME_PATTERN));
            orderVo.setAddress(item.getAddress());
            orderVo.setContact(item.getContact());
            orderVo.setReceiver(item.getReceiver());
            orderVo.setStatus(item.getStatus());
            orderVo.setUserId(item.getUserId());
            orderVo.setUsername(item.getUsername());
            orderVo.setTotal(item.getTotal());
            orderVoList.add(orderVo);
        });
        logger.info("orderList==>{}", orderVoList);
        commonUtil.getSession().setAttribute("orderList", orderVoList);
        return orderVoList;
    }

    /**
     * 根据id查询order
     * @param id
     * @return
     */
    @Override
    public Order getOrderById(Long id) {
        Order order = this.orderMapper.selectById(id);
        logger.info("order==>{}", order);
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderId(order.getOrderId());
        orderVo.setOrderNum(order.getOrderNum());
        orderVo.setCreateTime(DateUtils.format(order.getCreateTime(), DateUtils.DATE_TIME_PATTERN));
        orderVo.setUpdateTime(DateUtils.format(order.getUpdateTime(), DateUtils.DATE_TIME_PATTERN));
        orderVo.setAddress(order.getAddress());
        orderVo.setContact(order.getContact());
        orderVo.setReceiver(order.getReceiver());
        orderVo.setStatus(order.getStatus());
        orderVo.setUserId(order.getUserId());
        orderVo.setUsername(order.getUsername());
        orderVo.setTotal(order.getTotal());
        return order;
    }

    /**
     * 根据订单号模糊查询order
     * @param orderNum
     * @return
     */
    @Override
    public Order getOrderByOrderNum(String orderNum) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.like("orderNum", orderNum);
        Order order = this.orderMapper.selectOne(wrapper);
        logger.info("order==>{}", order);
        return order;
    }

    /**
     * 修改订单状态
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public Result setOrderStatus(Long orderId, String status) {
        logger.info("当前状态==>{}", status);
        Optional<OrderStatusEnum> first = Arrays.stream(OrderStatusEnum.values()).filter(item -> item.getTypeName().equals(status)).findFirst();
        Integer type = first.get().getType() + 1;
        Optional<OrderStatusEnum> firstStatus = Arrays.stream(OrderStatusEnum.values()).filter(item -> item.getType() == type).findFirst();
        String orderStatus = firstStatus.get().getTypeName();
        logger.info("orderStatus==>{}", orderStatus);
        try {
            logger.info("开始修改id为{}的订单", orderId);
//            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<Order>()
//                    .set("status", orderStatus)
//                    .set("updateTime", new Date())
//                    .eq("orderId", orderId);
//            int update = this.orderMapper.update(null, updateWrapper);
            Integer update = orderMapper.updateOrderStatus(orderId, orderStatus);
            if (update == EnableVariable.UNABLE){
                logger.info("修改状态失败");
                throw new ServiceException(ErrorCodeEnum.SQL_UPDATE_ERROR, "修改状态失败");
            }
        }catch (Exception e){
            logger.info("修改状态出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_UPDATE_ERROR, "修改状态出现异常");
        }
        logger.info("修改成功");
        return ResultUtil.ok("修改成功");
    }
}
